/**
 * Vue STOMP WebSocket封装工具类
 * 提供连接、订阅、发送消息等基础功能
 */
class StompClient {
  constructor(options = {}) {
    this.options = {
      brokerURL: 'ws://localhost:8080/ws', // 默认WebSocket地址
      reconnectDelay: 5000, // 重连延迟(ms)
      heartbeatIncoming: 4000, // 心跳接收间隔
      heartbeatOutgoing: 4000, // 心跳发送间隔
      debug: false, // 是否开启调试
      ...options
    };
    
    this.client = null;
    this.subscriptions = {};
    this.reconnectTimeout = null;
    this.connected = false;
  }

  /**
   * 连接WebSocket
   * @param {Function} onConnect 连接成功回调
   * @param {Function} onError 连接失败回调
   */
  connect(onConnect, onError) {
    if (this.client &amp;&amp; this.connected) {
      return;
    }

    // 使用SockJS和Stomp.js
    const socket = new SockJS(this.options.brokerURL);
    this.client = Stomp.over(socket);

    // 配置调试信息
    if (this.options.debug) {
      this.client.debug = (str) => console.log(str);
    } else {
      this.client.debug = () => {};
    }

    // 连接配置
    const headers = {
      ...this.options.headers,
      'heart-beat': `${this.options.heartbeatIncoming},${this.options.heartbeatOutgoing}`
    };

    this.client.connect(
      headers,
      (frame) => {
        this.connected = true;
        if (this.reconnectTimeout) {
          clearTimeout(this.reconnectTimeout);
          this.reconnectTimeout = null;
        }
        if (onConnect) onConnect(frame);
      },
      (error) => {
        this.connected = false;
        this._handleConnectionError(error, onError);
      }
    );
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.client &amp;&amp; this.connected) {
      this.client.disconnect(() => {
        this.connected = false;
        this.subscriptions = {};
      });
    }
  }

  /**
   * 订阅主题
   * @param {string} destination 订阅地址
   * @param {Function} callback 消息回调
   * @param {Object} headers 附加头信息
   * @returns {string} 订阅ID
   */
  subscribe(destination, callback, headers = {}) {
    if (!this.connected) {
      console.warn('Not connected to WebSocket');
      return null;
    }

    const sub = this.client.subscribe(destination, (message) => {
      callback(message.body, message);
    }, headers);

    const subId = `sub-${Date.now()}`;
    this.subscriptions[subId] = sub;
    return subId;
  }

  /**
   * 取消订阅
   * @param {string} subId 订阅ID
   */
  unsubscribe(subId) {
    const sub = this.subscriptions[subId];
    if (sub) {
      sub.unsubscribe();
      delete this.subscriptions[subId];
    }
  }

  /**
   * 发送消息
   * @param {string} destination 目标地址
   * @param {Object|string} body 消息体
   * @param {Object} headers 头信息
   */
  send(destination, body, headers = {}) {
    if (!this.connected) {
      console.warn('Not connected to WebSocket');
      return;
    }

    const payload = typeof body === 'string' ? body : JSON.stringify(body);
    this.client.send(destination, headers, payload);
  }

  /**
   * 处理连接错误
   * @private
   */
  _handleConnectionError(error, onError) {
    if (onError) onError(error);

    // 自动重连
    if (!this.reconnectTimeout) {
      this.reconnectTimeout = setTimeout(() => {
        this.connect();
      }, this.options.reconnectDelay);
    }
  }
}

// Vue插件安装
const StompPlugin = {
  install(Vue, options) {
    const stomp = new StompClient(options);
    Vue.prototype.$stomp = stomp;
    Vue.prototype.$stompClient = stomp;
  }
};

export { StompClient, StompPlugin };
